package com.twu.biblioteca;

import java.util.*;

public class Library {
    private Map<String, LibraryItem> availableItems;
    private Map<String, LibraryItem> borrowedItems;
    private Map<String, User> users;
    private User authenticatedUser;

    public Library(List<LibraryItem> availableItemsList, List<User> users) {
        this.borrowedItems = new LinkedHashMap<>();
        this.availableItems = new LinkedHashMap<>();
        this.users = new LinkedHashMap<>();
        this.authenticatedUser = null;

        for (LibraryItem item : availableItemsList) {
            availableItems.put(item.getCode(), item);
        }

        for (User user : users) {
            this.users.put(user.getLibraryNumber(), user);
        }
    }

    public Map<String, LibraryItem> getAvailableItems() {
        return availableItems;
    }

    public boolean checkoutItem(String code) {
        return moveItem(code, availableItems, borrowedItems);
    }

    public boolean returnItem(String code) {
        return moveItem(code, borrowedItems, availableItems);
    }

    private boolean moveItem(String code, Map<String, LibraryItem> fromMap, Map<String, LibraryItem> toMap) {
        if (fromMap.containsKey(code)) {
            toMap.put(code, fromMap.remove(code));
            return true;
        }

        return false;
    }

    public String getUserFriendlyBookList() {
        return getUserFriendlyList("Book");
    }

    public String getUserFriendlyMovieList() {
        return getUserFriendlyList("Movie");
    }

    private String getUserFriendlyList(String className) {
        StringBuilder stringBuilder = new StringBuilder();

        for (LibraryItem item : availableItems.values()) {
            if (item.getClass().getSimpleName().equals(className)) {
                stringBuilder.append(item.toString()).append('\n');
            }
        }

        return stringBuilder.toString();
    }

    public boolean authenticate(String libraryNumber, String password) {
        User retrievedUser;
        boolean success = false;

        if (users.containsKey(libraryNumber)) {
            retrievedUser = users.get(libraryNumber);
            success = retrievedUser.authenticate(password);

            if (success) {
                authenticatedUser = retrievedUser;
            }
        }

        return success;
    }

    public boolean isAuthenticated() {
        return authenticatedUser != null;
    }


    public String getUserInfo() {
        if (authenticatedUser == null) {
            return "No user authenticated.\n";
        }
        return authenticatedUser.contactInfo();
    }

    public User getAuthenticatedUser() {
        return authenticatedUser;
    }

    public void logout() {
        authenticatedUser = null;
    }
}
